import java.util.HashMap;

public class add {
    public int[] twoSum(int[] nums, int target) {
        // 创建一个哈希表来存储数组元素及其下标
        HashMap<Integer, Integer> map = new HashMap<>();

        // 遍历数组
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];  // 计算差值
            if (map.containsKey(complement)) {
                // 如果差值存在，返回当前元素的下标和差值对应元素的下标
                return new int[] { map.get(complement), i };
            }
            // 否则，将当前元素的值和下标存入哈希表
            map.put(nums[i], i);
        }

        // 如果没有找到答案（题目保证有解，所以这里不会执行）
        throw new IllegalArgumentException("No two sum solution");
    }

    public static void main(String[] args) {
       add solution = new add();
        int[] nums1 = {2, 7, 11, 15};
        int target1 = 9;
        int[] result1 = solution.twoSum(nums1, target1);
        System.out.println("Output: [" + result1[0] + ", " + result1[1] + "]");

        int[] nums2 = {3, 2, 4};
        int target2 = 6;
        int[] result2 = solution.twoSum(nums2, target2);
        System.out.println("Output: [" + result2[0] + ", " + result2[1] + "]");

        int[] nums3 = {3, 3};
        int target3 = 6;
        int[] result3 = solution.twoSum(nums3, target3);
        System.out.println("Output: [" + result3[0] + ", " + result3[1] + "]");
    }
}
